package com.uperform.coach.tdd.domain;

import com.uperform.coach.tdd.SystemDate;
import lombok.Getter;

import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;

@Getter
public class CycleTime {
    private String time;

    public CycleTime(String time) {
        this.time = time;
    }

    public void ensureValid() {
        if (!time.endsWith("月")) {
            throw new WrongCycleTimeException();
        }
    }

    public long next(long shouldExecuteAt) {
        ZonedDateTime zonedDateTime = Instant.ofEpochMilli(shouldExecuteAt).atZone(ZoneId.systemDefault());
        zonedDateTime = zonedDateTime.plusMonths(Integer.parseInt(time.substring(0, time.length() - 1)));
        return zonedDateTime.toInstant().toEpochMilli();
    }

    public long next(String shouldExecuteAt) {
        ZonedDateTime dateTime = LocalDate.parse(shouldExecuteAt, SystemDate.DATE_FORMATTER)
                .atStartOfDay()
                .atZone(ZoneId.systemDefault());
        if (dateTime.toInstant().toEpochMilli() < SystemDate.now()) {
            return next(dateTime.toInstant().toEpochMilli());
        }
        return dateTime.toInstant().toEpochMilli();
    }
}
